<?php
namespace app\controllers;

use app\models\User;
use backend\models\Admin;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;

class AuthController extends Controller
{
    public $redirect = '';

    public function beforeAction($action)
    {
        if (!parent::beforeAction($action))return false;
        $url = Yii::$app->request->get('redirect','');
        $this->redirect = empty($url) ? Yii::$app->getHomeUrl() : $url;

        return true;
    }

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'width' => 80,
                'height' => 20,
                'maxLength' => 4,
                'minLength' => 4,
                'offset' => 15,
                'transparent' => true,
                'testLimit' => 0,
            ],
        ];
    }

    /**
     * 执行登录
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        if(Yii::$app->request->isPost){
            $model = new User();
            $post = Yii::$app->request->post();
            $model->username = $post['username'];
            $model->password_hash = $post['password_hash'];

            $msg = $model->login() ?['e' => '0', 'm' => '恭喜你，登录成功','d' => $this->redirect] : ['e' => '1', 'm' => '很遗憾,登录失败', 'd' => $model->getErrors()];
            $this->ajaxReturn($msg);
        }
        return $this->render('login');
    }

    /**
     * 注册方法| 加载注册页面
     * @return string json字符串
     */
    public function actionRegister()
    {
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $model = new User();
            $model->username = $post['username'];
            $model->created_at = time();
            $model->updated_at = time();
            $model->email = isset($post['email']) ? $post['email'] : '';
            $model->password_hash = $post['password_hash'];

            if (!$model->validate())$this->ajaxReturn(['e' => '1','m' => '很遗憾，操作失败' , 'd' => $model->getErrors()]);

            $model->setPassword($post['password_hash']);
            $model->generateAuthKey();
            $model->generatePasswordResetToken();
            $msg = $model->save() ? ['e' => '0','m' => '恭喜您，操作成功','d' => $this->redirect] : ['e' => '1','m' => '很遗憾，操作失败'];
            $this->ajaxReturn($msg);
        }

        return $this->render('register');
    }

    # ajax 返回
    public function ajaxReturn($array)
    {
        echo json_encode($array,JSON_UNESCAPED_UNICODE);
        Yii::$app->end();
    }
}
